package com.yygo.webapp.controller;

import com.yygo.Constants;
import com.yygo.model.GrabRequest;
import com.yygo.model.Greeting;
import com.yygo.model.HelloMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * Created by tiansha on 2015/10/28.
 */
@Controller
public class MessageController {

    @Autowired
    public SimpMessagingTemplate template;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Destination destination;

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message, Principal principal) throws Exception {
        template.convertAndSendToUser("testuser", "/message", new Greeting("User Hello, " + message.getName() + "!")); // send to specific user
        //template.convertAndSend("/topic/greetings", greeting); // broadcast
        return new Greeting("Topic Hello, " + message.getName() + "!");
    }

    @MessageMapping("/grabTicket")
    public void grabTicket(final GrabRequest grabRequest, final Principal principal) throws Exception {
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                Message message = session.createMessage();
                message.setLongProperty("reqId", grabRequest.getReqId());
                message.setStringProperty("type", Constants.MSG_TYPE_GRAB_TICKET);
                message.setStringProperty("requestor", principal.getName());
                return message;
            }
        });
    }

}
